<template>
  <el-dialog :model-value="dialogVisible" :title="title" :before-close="handleClose" :z-index="1000" width="450px" draggable>
    <div class="tree">
      <ZTree :id="treeId" :zNodes="zNodes" :enable-check="true" />
    </div>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="UserDrawer">
/* eslint-disable */
// @ts-nocheck
import { getOrgTree } from "@/api/modules/common";
import { ref, onMounted, watch, nextTick } from "vue";
import { ElMessage } from "element-plus";
import ZTree from "@/components/ZTree/index.vue";
import { saveDepartmentRights, saveMapRights, saveRuleGroupRights, saveRoomMapRights } from "@/api/modules/user";

const treeId = ref("tree");
const loading = ref(false);

const props = defineProps<{
  dialogVisible: boolean;
  title: string;
  zNodes: any[];
  rights: any[];
  handleType: number;
  handleClose: () => void;
  optId: string;
}>();

watch(
  () => props.rights,
  nV => {
    if (nV) {
      let zTree = $.fn.zTree.getZTreeObj(treeId.value);
      zTree.cancelSelectedNode();
      for (let i = 0; i < nV.length; i++) {
        const node = zTree.getNodeByParam("id", parseInt(nV[i]));
        if (node != null) {
          zTree.checkNode(node, true, false);
        }
      }
      // zTree.expandAll(true);
      const nodes = zTree.getNodes();
      zTree.expandNode(nodes[0], true);
    }
  }
);

/**
 * 提交信息
 */
const handleSubmit = async () => {
  const rightsMap = new Map([
    [2, saveDepartmentRights],
    [3, saveMapRights],
    [4, saveRuleGroupRights],
    [6, saveRoomMapRights]
  ]);
  const zTree = $.fn.zTree.getZTreeObj(treeId.value);
  const checkedNodes = zTree.getCheckedNodes(true);
  if (!checkedNodes.length) {
    ElMessage.error("请勾选权限");
    return false;
  }
  loading.value = true;
  try {
    const res = await rightsMap.get(props.handleType)({ id: props.optId, clause: checkedNodes.map(item => item.id).join(":") });
    ElMessage.success("更新成功");
    props.handleClose();
    loading.value = false;
  } catch (error) {
    loading.value = false;
    console.log(error);
  }
};
</script>

<style lang="scss" scoped>
.tree {
  height: 80vh;
  overflow-y: auto;
}
</style>
